package com.fishingwithme.android.ui.screens.map.handlers

import android.util.Log
import com.fishingwithme.android.R
import com.fishingwithme.android.data.model.Spot
import com.fishingwithme.android.navigation.FishingNavigation
import com.fishingwithme.android.ui.screens.map.CustomMarkerDrawer

/**
 * 清理处理器 - 用于清理地图数据和元素
 */
class MapRefreshHandler : BaseHandler() {
    override val key: String = "refresh_spots"
    override val icon: Int = R.mipmap.refresh  // 使用"delete"图标表示清理操作
    override val showMenu: Boolean = false
    override var initializeData: Boolean = true

    // Map to store spot information for each marker
    private val markerSpotMap =
        mutableMapOf<com.tencent.tencentmap.mapsdk.maps.model.Marker, Spot>()

    override fun active() {
        Log.d("MapRefreshHandler", "active() called")

        // Check if map and context are available
        if (map == null || mapContext == null) {
            Log.w("MapRefreshHandler", "Map or context is null, skipping active")
            return
        }

        // Log the data in the context
        Log.d("MapRefreshHandler", "Map context data size: ${mapContext?.data?.size}")
        mapContext?.data?.forEach { (key, value) ->
            Log.d("MapRefreshHandler", "Map context data key: $key, value: $value")
        }

        // Check if map is still valid
        try {
            mapContext?.clearAllElements()
        } catch (e: Exception) {
            Log.w("MapRefreshHandler", "Map context is no longer valid", e)
            return
        }

        markerSpotMap.clear()

        val spots: List<Spot> = mapContext?.data?.get("spots") as? List<Spot> ?: emptyList()
        Log.d("MapRefreshHandler", "Found ${spots.size} spots to display")

        // Set up marker click listener for custom markers
        try {
            map?.setOnMarkerClickListener { marker ->
                // Handle click on custom marker
                Log.d("MapRefreshHandler", "Custom marker clicked")

                // Find the associated spot for this marker
                val spot = markerSpotMap[marker]
                if (spot != null) {
                    // Navigate to HOME screen with spot ID using EventBus
                    val homeRoute = "${FishingNavigation.HOME}?id=${spot.id}"
                    mapController?.onNavigateBack?.invoke(homeRoute)

                    Log.d(
                        "MapRefreshHandler",
                        "Posted navigation event to HOME with spot ID: ${spot.id}"
                    )
                }

                true // Return true to consume the event
            }
        } catch (e: Exception) {
            Log.w("MapRefreshHandler", "Error setting marker click listener", e)
            return
        }

        // Create custom marker drawer
        val markerDrawer = CustomMarkerDrawer()

        spots.forEach { spot ->
            // Display all spots with marker on the map from context data
            if (spot.latitude != null && spot.longitude != null) {
                val latLng =
                    com.tencent.tencentmap.mapsdk.maps.model.LatLng(spot.latitude, spot.longitude)

                // Create custom marker bitmap with spot name to display on top
                val customMarkerBitmap =
                    markerDrawer.createMarkerBitmap(spot.name ?: "Unknown", context!!)

                // Add custom marker on top of the original marker
                if (customMarkerBitmap != null) {
                    val customMarkerOptions =
                        com.tencent.tencentmap.mapsdk.maps.model.MarkerOptions(latLng)
                            .icon(customMarkerBitmap)
                            .anchor(0.5f, 0.5f) // Center the marker
                            .zIndex(1f) // Ensure it's on top

                    try {
                        val customMarker = map?.addMarker(customMarkerOptions)

                        // Store the spot information with the marker
                        customMarker?.let {
                            markerSpotMap[it] = spot
                            addMarkerToMap(it)
                        }
                    } catch (e: Exception) {
                        Log.w("MapRefreshHandler", "Error adding marker for spot: ${spot.name}", e)
                    }
                }
            } else {
                Log.d("MapRefreshHandler", "Skipping spot ${spot.name} due to missing coordinates")
            }
        }
        Log.d("MapRefreshHandler", "Finished adding markers")
    }

    override fun removeListeners() {
        super.removeListeners()
        // Remove marker click listener
        try {
            map?.setOnMarkerClickListener(null)
        } catch (e: Exception) {
            Log.w("MapRefreshHandler", "Error removing marker click listener", e)
        }
        // Clear the marker-spot map
        markerSpotMap.clear()
    }
}